package cmbchina.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HTTP;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 作用：
 * Author: admin
 * Date:16-12-1
 */
public class FlowHttpRequestUtils {

    private static final Logger logger = LoggerFactory.getLogger(FlowHttpRequestUtils.class);
    public static Properties appConfig = AppConfig.getInstance().getConfig();
    public static final String url = appConfig.getProperty("flow_url");
    public static final String flow_api_Url = appConfig.getProperty("flow_api_Url");
    public static final int port = Integer.parseInt(appConfig.getProperty("flow_port"));
//    public static final String flowable_password = appConfig.getProperty("flowable_password");

    /**
     * get请求
     * @param apiUrl api路径
     * @return
     */
    public static Map<String,Object> httpRequestGet(String apiUrl){

        String protocol = "http";
        apiUrl = flow_api_Url+apiUrl;
        String userName = "";
        String password ="";
        Map<String,Object> resultMap = null;

        HttpHost targetHost = new HttpHost(url, port, protocol);

        DefaultHttpClient httpclient = initHttpClient(targetHost, userName, password);
        BasicHttpContext localcontext = initHttpContext(targetHost);

        /*请求*/
        String path = protocol+"://"+url+":"+port+apiUrl;
        HttpGet httpGet = new HttpGet(path);

        httpGet.setHeader("Content-Type", "application/json");
        httpGet.setHeader("accept","application/json");

        try {

            HttpResponse response = httpclient.execute(targetHost, httpGet, localcontext);
            resultMap = readResult(response);

        }catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }finally {
            httpGet.releaseConnection();
            httpclient.getConnectionManager().shutdown();
        }

        return resultMap;

    }

    /**
     * post请求
     * @param apiUrl api路径
     * @param params 参数
     * @return
     */
    public static Map<String,Object> httpRequestPost(String apiUrl,String params){

        String protocol = "http";
        String userName = "";
        String password ="";
        apiUrl = flow_api_Url+apiUrl;
        Map<String,Object> resultMap = null;

        HttpHost targetHost = new HttpHost(url, port, protocol);
        DefaultHttpClient httpclient = initHttpClient(targetHost, userName, password);
        BasicHttpContext localcontext = initHttpContext(targetHost);

        /*设置post参数*/
        String path = protocol+"://"+url+":"+port+apiUrl;
        HttpPost httpPost = new  HttpPost(path);
        httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
        httpPost.setHeader("accept","application/json");

        try {

            if(params != null && params.length() > 0) {
                StringEntity stringEntity = new StringEntity(params, HTTP.UTF_8);
                httpPost.setEntity(stringEntity);
            }

            HttpResponse response = httpclient.execute(targetHost, httpPost, localcontext);
            resultMap = readResult(response);

        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        } finally {
            httpPost.releaseConnection();
            httpclient.getConnectionManager().shutdown();
        }

        return resultMap;

    }



    /**
     * 初始化客户端
     * @param targetHost
     * @param userName
     * @param password
     * @return
     */
    public static DefaultHttpClient initHttpClient (HttpHost targetHost,String userName,String password) {

        DefaultHttpClient httpclient = new DefaultHttpClient();
       /* 请求超时*/
        httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000*60*2);
        /*读取超时*/
        httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 1000*60*60);
        /*请求认证*/
        httpclient.getCredentialsProvider().setCredentials(
                new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials(userName, password));

        return httpclient;

    }

    /**
     * 初始化httpcontext
     * @param targetHost
     * @return
     */
    public static BasicHttpContext initHttpContext(HttpHost targetHost) {

        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(targetHost, basicAuth);
        BasicHttpContext localcontext = new BasicHttpContext();
        localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

        return localcontext;

    }

    /**
     *
     * @param response
     * @return
     */
    public static Map<String,Object> readResult(HttpResponse response){

        Map<String,Object> resultMap = new HashMap<String, Object>();

        HttpEntity entity = response.getEntity();
        BufferedReader  reader = null;
        StringBuffer sb = new StringBuffer();

        try {

            reader = new BufferedReader(new InputStreamReader(entity.getContent(),"utf-8"));
            String buffer  = "";
            while((buffer = reader.readLine())!=null){
                sb.append(buffer);
            }

            System.out.println("返回结果"+buffer);
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                reader.close();
            } catch (IOException e) {
                logger.error(e.getMessage());
            }
        }

        int statusCode = response.getStatusLine().getStatusCode();
        resultMap.put("statusCode",statusCode);
        logger.debug("StatusCode:" + statusCode);
        /*请求返回接口拼接*/
        String content = sb.toString();
        resultMap.put("result",content);
        logger.debug("result:" + content);

        return resultMap;

    }

    public static void main(String [] args){
        Map<String,Object> params = new LinkedHashMap<String, Object>();
        params.put("processInstId","67501");
        params.put("state","2");
        String mapJakcson = "{\"id\":null,\"processInstId\":\"72501\",\"fromInfo\":null,\"result\":null,\"createTime\":null,\"lastUpdateTime\":null,\"version\":null,\"resultCode\":null,\"resultState\":\"1\",\"taskId\":null,\"taskDefinitionKey\":\"sid-CE99507A-829E-4C1F-A403-AD9998C59DCB\",\"taskName\":null}";
        FlowHttpRequestUtils.httpRequestPost("/api/flow-forms",mapJakcson );
//        httpRequestPost("/oplus-udp-0.0.1-SNAPSHOT/api/flows",params);
//        httpRequestPost()
    }


}
